﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TextString.WindowsFormsApp
{
    public partial class FormStartup : Form
    {
        public FormStartup()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            var bytes = Encoding.UTF8.GetBytes(textBox1.Text);

            foreach (var b in bytes)
            {
                richTextBox1.AppendText(Convert.ToString(b, 2));
                richTextBox1.AppendText(Environment.NewLine);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            var range = 8;
            var text = textBox1.Text;
            var count = Math.DivRem(text.Length, range, out var result);
            var bytes = new byte[count + (result == 0 ? 0 : 1)];
            for (int i = 0; i < count; i++)
            {
                var b = text.Substring(i * range, range);
                bytes[i] = Convert.ToByte(b, 2);
            }

            if (result != 0)
            {
                var b = text.Substring(count * range, range);
                bytes[count] = Convert.ToByte(b, 2);
            }

            richTextBox1.Text = Encoding.UTF8.GetString(bytes);
        }
    }
}
